package main

import (
	"time"
	"fmt"
)
func work(i int,c chan int){
	for  n := range c {
		time.Sleep(1*time.Second)
		fmt.Printf("%d,%d\n",i,n)
	}
}
func createWorker(i int ) chan<- int{
	c := make(chan int)
	go work(i,c)
	return c
}

func generator() chan int{
	c := make(chan int)
	go func() {
		i := 0
		for{
			time.Sleep(time.Duration(1500) * time.Millisecond)
			c <- i
			i ++
		}

	}()
	return c
}
/*channel 为 nil的话 不会传值*/
func main() {
	var c1, c2 = generator(),generator()
	var worker = createWorker(0)

	n := 0

	var values []int // 用来接收数据，排队让人消耗
	afterTime := time.After(8 * time.Second) // 10秒之后
	tick := time.Tick(time.Second) //任务,每秒
	for{
		var activeWorker chan<- int //nil channel 是不会发送数据的
		var activeValue int
		//  c1,c2有值 就不让channel为nil ,就可以发送数据了
		if  len(values) > 1 {
			activeWorker = worker
			activeValue = values[0]
		}

		select {
		case n = <-c1:
			values = append(values, n)
		case n = <-c2:
			values = append(values, n)
		case activeWorker <- activeValue:
			// 发送完数据置false
			values = values[1:]
		// 800毫秒之内没生成数据就打印timeout
		case <- time.After(2000 * time.Millisecond):
			fmt.Println("timeout")
		// 每秒打印一次长度
		case <- tick:
			fmt.Println("queeu len = ",len(values))
		case after := <- afterTime:
			fmt.Println("结束，time = ",after)
			return
		}
	}
}
